<template>
  <div>
    <div class="file-header">
      <div class="breadcrumb">
        <span v-for="(e, i) in paths" :key="i">
          <el-button type="text" @click="goLevel(e, i)">{{ e.name }}</el-button>
          {{ `${i != paths.length - 1 ? "/" : ""}` }}
        </span>
      </div>
      <div class="switch">
        <btn-upload
          v-if="!is_public && listShow"
          class="add-btn"
          :type="type"
          :biz_id="biz_id"
          :relative_path="relativePath"
          @inlabelsActivefo="info"
        />
        <a
          href="javascript:;"
          :class="['btn-pic', { acticv: !listShow }]"
          @click="listShow = false"
        ></a>
        <a href="javascript:;" :class="['btn-lis', { acticv: listShow }]" @click="listShow = true"></a>
      </div>
    </div>
    <div class="scroll-box">
      <el-table :data="tableData" v-if="listShow">
        <el-table-column prop="name" label="名称">
          <template slot-scope="{ row }">
            <span @dblclick="goPath($event, row)">
              <!-- {{ row.name }} -->
              <preview :row="row" :is_public="is_public" style="height: 20px" />
            </span>
            <!-- <span @click="preview(row)">{{ row.name }}</span> -->
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="文件大小" prop="size">
          <template slot-scope="{ row }">{{ formatFileSize(row) }}</template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="修改时间" prop="modify_time" />
        <el-table-column label="操作" width="150px" align="center" header-align="center">
          <template slot-scope="{ row }">
            <div class="btn_box">
              <el-button
                type="text"
                v-if="type == 'model' && isModelFile(row)"
                @click="view(row)"
              >网络结构</el-button>
              <el-button type="text" @click="free(row)">分享</el-button>
              <el-button type="text" @click="download(row)">下载</el-button>
              <el-popover placement="top" width="80" trigger="click" v-model="row.visible">
                <p>您确定要删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="row.visible = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="del(row)">确定</el-button>
                </div>
                <el-button type="text" slot="reference">删除</el-button>
                <!-- <el-button slot="reference" type="danger" size="mini">删除</el-button> -->
                <!-- <i slot="reference" class="el-icon-delete delete-btn" /> -->
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--  v-infinite-scroll="load" -->
      <ul class="large-icon" v-else>
        <li v-for="(e, i) in tableData" :key="i" @contextmenu.prevent="contextmenu($event, e)">
          <div class="file-item" @dblclick="goPath($event, e)">
            <preview
              :row="e"
              :tableData="tableData"
              :index="i"
              :is_public="is_public"
              class="large-icon-preview"
              isLarge="1"
            />
            <img :src="selectIcon(e)" alt v-if="handleClass(e) != 'pic'" class="file-icon" />
            <img class="file-icon" :src="e.addr" alt v-if="handleClass(e) == 'pic'" />
          </div>
          <el-tooltip effect="dark" placement="bottom-start" :content="e.name">
            <p class="name">{{ e.name }}</p>
          </el-tooltip>
        </li>
        <li class="large-icon-add" v-if="!is_public">
          <span>+</span>
          <btn-upload
            class="add-btn"
            :type="type"
            :biz_id="biz_id"
            :relative_path="relativePath"
            @info="info"
          />
        </li>
      </ul>
    </div>
    <div class="pagination-box" v-if="Pagedata.total > Pagedata.page_size">
      <el-pagination
        background
        class="pagination"
        layout="total, prev, pager, next, jumper"
        :page-size="Pagedata.page_size"
        :current-page.sync="Pagedata.pageNum"
        @current-change="handleCurrentChange"
        :total="Pagedata.total"
      ></el-pagination>
    </div>

    <DialogBox title="运行" :visible="showRunDialog" :confirm="commitRun" :close="cancelRun">
      <el-form class="form myself-form" ref="simulationForm" :model="runForm" label-width="80px">
        <el-form-item label="运行命令">
          <el-input type="text" v-model="runForm.command" />
        </el-form-item>
      </el-form>
    </DialogBox>
  </div>
</template>

<script>
import DialogBox from "@/components/module/dialog-box.vue";
// getFileList
import { gameExperimentRunFile } from "@/api/gameExperiment";
import { notebookRunFile } from "@/api/notebook";
import {
  getPageFileList,
  getDownloadKey,
  getFree,
  delFile,
  previewFile
} from "@/api/file";
import { zipFormat, mediaFormat } from "@/utils/maps";
import btnUpload from "./modules/btnUploader";
import preview from "./modules/preview";
import { domain } from "@/config";
import { Base64 } from "js-base64";
// import { InfiniteScroll } from "element-ui";
// console.log(InfiniteScroll)
export default {
  name: "FileList",
  props: [
    "biz_id",
    "relative_path",
    "type",
    "is_public",
    "pathName",
    "beforeDel"
  ],
  data() {
    return {
      myInfo: {},
      tableData: [],
      Pagedata: {},
      paths: [],
      listShow: false,
      relativePath: "",
      showPreviewSrc: "",
      currData: null,
      myMap: {},
      modelFileType: [
        ".onnx",
        ".pb",
        ".meta",
        ".tflite",
        ".lite",
        ".tfl",
        ".keras",
        ".h5",
        ".hd5",
        ".hdf5",
        ".model",
        ".mar",
        ".params",
        ".param",
        ".armnn",
        ".mnn",
        ".ncnn",
        ".tnnproto",
        ".tmfile",
        ".ms",
        ".nn",
        ".uff",
        ".rknn",
        ".xmodel",
        ".paddle",
        ".pdmodel",
        ".pdparams",
        ".dnn",
        ".cmf",
        ".mlmodel",
        ".caffemodel",
        ".pbtxt",
        ".prototxt",
        ".pkl",
        ".pt",
        ".pth"
      ],
      showRunDialog: false,
      runForm: {
        command: ""
      }
    };
  },
  watch: {
    async biz_id(val) {
      console.log(val);
      await this.initParam(this.relative_path);
      this.getData();
    }
  },
  components: {
    btnUpload,
    preview,
    DialogBox
  },
  methods: {
    view(row) {
      let path =
        `${domain.split(":")[1]}:31998/?modelFile=/models/` +
        row.path.slice(10);
      window.open(path, "_blank");
    },
    isModelFile(row) {
      console.log("path", row.path);
      let ext = row.path.split(".").pop();
      console.log("ext", ext);
      let exttmp = "." + ext;
      return this.modelFileType.includes(exttmp);
    },
    up() {
      this.$parent.up();
    },
    handleClass({ dir, suffix }) {
      if (dir) return "dir";
      if (zipFormat[suffix]) return "zip";
      if (mediaFormat[suffix]) return mediaFormat[suffix];
      return "text";
    },
    async showImage(e) {
      let key = await getDownloadKey({
        biz_id: e.biz_id,
        cache_expire_type: "temporary",
        relative_paths: [e.path.split(e.biz_id)[1]],
        temporary_expire_duration: 5000,
        type: e.type,
        use_os_command_to_compress: true,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public,
        with_src_dir: true
      });
      this.showPreviewSrc = `${domain}file/v1/file/download?fileId=${key.data.file_id}`;
      await this.$set(e, "addr", this.showPreviewSrc); //会重新更新item到视图
    },
    next() {
      this.$parent.next();
    },
    contextmenu(event, row) {
      this.$contextmenu.destroy();
      let items = [
        {
          label: "删除",
          icon: "delete",
          onClick: () => {
            this.del(row);
          }
        }
      ];
      if (!row.dir) {
        items.unshift({
          label: "下载",
          onClick: () => {
            this.download(row);
          }
        });
      }

      if (
        !row.dir &&
        (this.$route.path.includes("gameExperiment") ||
          this.$route.path.includes("notebook") ||
          this.$route.path.includes("modelReinforcement") ||
          this.$route.path.includes("gameDeepLearning") ||
          this.$route.path.includes("gameDistributedTraining"))
      ) {
        items.unshift({
          label: "运行",
          onClick: () => {
            this.showRunDialog = true;
            this.runForm.command = row.path
              .replace(`/platform/${this.myInfo.id}`, "")
              .replace(`/${this.$route.query.id}`, "");
          }
        });
      }

      this.$contextmenu({
        items,
        event,
        zIndex: 999,
        minWidth: 100
      });
    },
    load() {
      console.log(this.Pagedata.page_num);
    },
    async initParam(relative_path) {
      this.myInfo = await this.$myInfo(this);
      this.Pagedata = {
        biz_id: this.biz_id,
        is_public: this.is_public,
        relative_path,
        type: this.type,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public,
        page_num: 1,
        page_size: 20,
        current: 1
      };
      return;
    },
    async getData() {
      let res = await getPageFileList(this.Pagedata);
      // let res2 = await getFileList(this.Pagedata)
      // console.log(res2)
      console.log(res);
      this.tableData = res.data.list;
      this.tableData.forEach(item => {
        if (this.handleClass(item) == "pic") {
          this.showImage(item);
          console.log(item);
        }
      });
      this.Pagedata.total = res.data.total;
      this.$forceUpdate();
    },
    info() {
      this.getData();
    },
    goPath($event, { dir, name, path }) {
      $event.stopPropagation();
      if (!dir) return;
      this.Pagedata.relative_path = path.split(this.biz_id)[1];
      this.paths.push({
        name,
        relative_path: path.split(this.biz_id)[1]
      });
      this.relativePath = path.split(this.biz_id)[1];
      //console.log(path)
      //console.log("relativePath1", this.relativePath)
      this.getData();
    },
    goLevel(e, i) {
      this.Pagedata.relative_path = e.relative_path;
      this.paths.splice(i + 1);
      this.relativePath = e.relative_path;
      this.getData();
    },
    handleCurrentChange(val) {
      this.Pagedata.current = val;
      this.Pagedata.page_num = this.Pagedata.current;
      this.getData();
    },
    async free(row) {
      console.log(row.path.split(this.biz_id)[1]);
      let relative_paths = [row.path.split(this.biz_id)[1]];
      let response = await getFree({
        biz_id: this.biz_id,
        cache_expire_type: "temporary",
        relative_paths,
        temporary_expire_duration: 5000,
        type: this.type,
        use_os_command_to_compress: true,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public,
        with_src_dir: true
      });
      console.log(response);

      response.status &&
        this.$message({
          type: "success",
          message: response.data
        });
    },
    async download(row) {
      console.log(row.path.split(this.biz_id)[1]);
      let relative_paths = [row.path.split(this.biz_id)[1]];
      let key = await getDownloadKey({
        biz_id: this.biz_id,
        cache_expire_type: "temporary",
        relative_paths,
        temporary_expire_duration: 5000,
        type: this.type,
        use_os_command_to_compress: true,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public,
        with_src_dir: true
      });
      location.href = `${domain}file/v1/file/download?fileId=${key.data.file_id}`;
    },
    async commitRun(row) {
      console.log(row);

      if (process.env.VUE_APP_VERSIONS === "gamma") {
        await gameExperimentRunFile({
          command: this.runForm.command,
          game_id: this.$route.query.id
        });
      } else if (process.env.VUE_APP_VERSIONS === "delta") {
        await notebookRunFile({
          command: this.runForm.command,
          game_id: this.$route.query.id
        });
      }

      this.cancelRun();
    },
    cancelRun() {
      this.showRunDialog = false;
      this.runForm.command = "";
    },
    formatFileSize({ size, dir }) {
      if (dir) {
        return "-";
      }
      if (size < 1024) {
        return size + "B";
      } else if (size < 1024 * 1024) {
        let temp = size / 1024;
        temp = temp.toFixed(2);
        return temp + "KB";
      } else if (size < 1024 * 1024 * 1024) {
        let temp = size / (1024 * 1024);
        temp = temp.toFixed(2);
        return temp + "MB";
      } else {
        let temp = size / (1024 * 1024 * 1024);
        temp = temp.toFixed(2);
        return temp + "GB";
      }
    },
    async del(row) {
      // let res = await this.$isDel();
      // if (res) {
      let relative_path = row.path.split(this.biz_id)[1];
      let data = {
        biz_id: this.biz_id,
        relative_path,
        type: this.type,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public
      };
      await delFile(data);
      this.getData();
      // }
    },
    async preview(row) {
      console.log(row);

      let encodedRelativePath = encodeURIComponent(
        Base64.encode(row.path.split(this.biz_id)[1])
      );
      let res = await previewFile({
        bizId: this.biz_id,
        encodedRelativePath,
        type: this.type,
        user_id: this.is_public ? "public" : this.myInfo.id,
        is_cross_user_dir: this.is_public
      });
      console.log(res);
    },
    selectIcon({ dir, suffix, name }) {
      console.log("name", name, suffix, this.biz_id, this.relativePath);
      if (dir) {
        return require("@/assets/img/file-icon/folder.png");
      }
      let format = {
        pic: require("@/assets/img/file-icon/image.png"),
        video: require("@/assets/img/file-icon/big-video.png"),
        voice: require("@/assets/img/file-icon/big-voice.png"),
        markdown: require("@/assets/img/file-icon/big-text.png"),
        python: require("@/assets/img/file-icon/big-text.png"),
        shell: require("@/assets/img/file-icon/big-text.png"),
        yaml: require("@/assets/img/file-icon/big-text.png"),
        css: require("@/assets/img/file-icon/big-text.png"),
        json: require("@/assets/img/file-icon/big-text.png"),
        zip: require("@/assets/img/file-icon/big-zip.png")
      };
      // if (mediaFormat[suffix] == "pic") {
      //   let imgPath = this.relativePath+"/"+name
      //   let a= `${domain}file/v1/file/preview/${this.myInfo.id
      //     }/${this.type}/${this.biz_id}/${encodeURIComponent(Base64.encode(imgPath))
      //     }`
      //   console.log("ready",a)
      //   return a
      // }
      if (zipFormat[suffix]) return format["zip"];
      if (mediaFormat[suffix]) return format[mediaFormat[suffix]];
      return require("@/assets/img/file-icon/big-text.png");
    }
  },
  async mounted() {
    await this.initParam(this.relativePath);
    this.getData();
    let root_path = this.type == "workspace" ? "/workspace" : "根路径";
    let root = this.pathName ? this.pathName : root_path;
    this.paths = [
      {
        name: root,
        relative_path: this.relative_path
      }
    ];
    //this.relativePath = this.relative_path
    console.log("relativePath", this.relativePath);
  }
};
</script>

<style lang="less" scoped>
.scroll-box {
  overflow: auto;
  max-height: 460px;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.1);
  }

  &::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.06);
  }
}

.file-header {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;

  .breadcrumb {
    line-height: 40px;
    padding-left: 20px;
  }
}

.switch {
  overflow: hidden;
  padding-right: 20px;

  a {
    float: left;
    width: 20px;
    height: 20px;
    margin-left: 14px;
    margin-top: 10px;
    background-color: #767676;
  }

  .btn-pic {
    mask: url(~@/assets/img/file-icon/btn-pic.svg);
    mask-size: 20px 20px;
  }

  .btn-lis {
    mask: url(~@/assets/img/file-icon/btn-lis.svg);
    mask-size: 20px 20px;
  }

  .acticv {
    background-color: #409eff;
  }

  .add-btn {
    float: left;
  }
}

.large-icon {
  display: grid;
  grid-gap: 10px;
  justify-content: space-between;
  justify-items: center;
  grid-template-columns: repeat(auto-fill, 131px);
  padding-bottom: 10px;

  li {
    width: 80px;
    margin: 40px 40px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .file-item {
    position: relative;
    height: 56px;
    display: flex;
    justify-content: center;

    .large-icon-preview {
      position: absolute;
      left: 0;
      top: 0;

      /deep/ .name-icon {
        height: 56px;
        opacity: 0;
      }
    }

    .file-icon {
      height: 56px;
    }
  }

  .name {
    padding-top: 8px;
    line-height: 24px;
    color: #3d3d3d;
    width: 95%;
    overflow: hidden;
    text-align: center;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .large-icon-add {
    position: relative;

    span {
      width: 80px;
      height: 80px;
      font-size: 22px;
      border-radius: 4px;
      display: block;
      line-height: 80px;
      text-align: center;
      border: 1px solid #dcdfe6;
    }

    .add-btn {
      width: 80px;
      height: 80px;
      position: absolute;
      left: 0;
      top: 0;

      /deep/ .add-button {
        width: 80px;
        height: 80px;
        opacity: 0;
      }
    }
  }
}

.btn_box {
  display: flex;
  justify-content: center;
}
</style>
